﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DataCentral.Dataset;
using CommonData;

namespace DataCentral.UserControls
{
    public partial class UserMaintenanceControl : CommonCenterControl
    {
        public UserMaintenanceControl()
        {
            InitializeComponent();
        }

        public override int SaveDataOnControl()
        {
            int iResult = 0;
            try
            {
                this.Validate();
                this.bsUser.EndEdit();
                iResult = this.tableAdapterManager.UpdateAll(this.dsBET);
                if (iResult < 0)
                {
                    MessageClass.ShowErrorMessage(ConstantClass._Error_SaveDataError);
                }
                else if (this.Parent is GroupControl)
                {
                    string strCaption = ((GroupControl)Parent).Text;
                    ((GroupControl)Parent).Text = strCaption.Substring(0, strCaption.IndexOf(ConstantClass._STR_START));
                    base.IsDataChanged = false;
                    btnSave.Enabled = false;
                }
            }
            catch (Exception exp)
            {
                //CommonFunctions.AddException("Cập nhật người dùng không thành công", exp);
            }
            return iResult;
        }

        private void DataHasChanged()
        {
            base.IsDataChanged = true;
            if (this.Parent is GroupControl && !((GroupControl)Parent).Text.EndsWith(ConstantClass._STR_START))
                ((GroupControl)Parent).Text += ConstantClass._STR_START;
            btnSave.Enabled = true;
        }

        private void UserMaintenanceControl_Load(object sender, EventArgs e)
        {
            ValueListClass clValueList = new ValueListClass();
            repRoleID.DataSource = clValueList.GetRoleList();
            daUser.Fill(dsBET.Users);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveDataOnControl();
        }

        private void viewUser_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            MessageClass.ShowInformationMessage("Vì lí do bảo mật hệ thống (toàn bộ mật khẩu sẽ được mã hóa), mật khẩu mặc định ban đầu là:12345.\r\nSau khi được tạo tài khoản, bạn vào chức năng thay đổi mật khẩu để thay đổi mật khẩu của mình.");
            DataCentralDataset.UsersRow userRow;
            if (viewUser.GetFocusedDataRow() is DataCentralDataset.UsersRow)
            {
                userRow = (DataCentralDataset.UsersRow)viewUser.GetFocusedDataRow();
                userRow.UserID = Guid.NewGuid();
                userRow.UserName = string.Empty;
                userRow.Password = CommonFunctions.EncodeTo64("12345");
                userRow.Description = string.Empty;
                userRow.CreatedDate = DateTime.Now;
                userRow.CreatedUserID = StaticClass.GetUserLogin();
                userRow.LastUpdatedDate = DateTime.Now;
                userRow.LastUpdatedUserID = StaticClass.GetUserLogin();
            }
        }

        private bool IsUserExisted(DataCentralDataset.UsersRow drUser)
        {
            bool isExist = false;
            foreach (DataCentralDataset.UsersRow drSelect in dsBET.Users)
            {
                if (drSelect.UserID != drUser.UserID && drSelect.UserName.Equals(drUser.UserName))
                {
                    isExist = true;
                    break;
                }
            }
            return isExist;
        }

        private void viewUser_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            DataCentralDataset.UsersRow userRow;

            if (viewUser.GetFocusedDataRow() is DataCentralDataset.UsersRow)
            {
                viewUser.ClearColumnErrors();
                userRow = (DataCentralDataset.UsersRow)viewUser.GetFocusedDataRow();
                if (userRow.IsNull("Password") || string.IsNullOrEmpty(userRow.Password))
                {
                    viewUser.SetColumnError(colPassword, ConstantClass._Error_PassNotBlank);
                    viewUser.FocusedColumn = colPassword;
                    e.Valid = false;
                }
                if (userRow.IsNull("RoleID") || userRow.RoleID < 0)
                {
                    viewUser.SetColumnError(colRoleID, ConstantClass._Error_RoleNotBlank);
                    viewUser.FocusedColumn = colRoleID;
                    e.Valid = false;
                }
                if (userRow.IsNull("UserName") || string.IsNullOrEmpty(userRow.UserName))
                {
                    viewUser.SetColumnError(colUserName, ConstantClass._Error_UserNotBlank);
                    viewUser.FocusedColumn = colUserName;
                    e.Valid = false;
                }
                else if (!string.IsNullOrEmpty(userRow.UserName) && IsUserExisted(userRow))
                {
                    viewUser.SetColumnError(colUserName, ConstantClass._Error_UserNotExist);
                    viewUser.FocusedColumn = colUserName;
                    e.Valid = false;
                }

                if (e.Valid)
                {
                    userRow.LastUpdatedDate = DateTime.Now;
                    userRow.LastUpdatedUserID = StaticClass.GetUserLogin();
                }
            }
        }

        private void viewUser_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            DataHasChanged();
        }

        private void viewUser_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                btnDelete.PerformClick();
            }
            else if (e.KeyCode == Keys.Insert)
            {
                btnAdd.PerformClick();
            }
            else if (e.Control && e.KeyCode == Keys.S)
            {
                btnSave.PerformClick();
            }
        }

        private void viewUser_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            MessageClass.ShowErrorMessage(ConstantClass._Error_InvalidData);
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
        }

        private void viewUser_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            btnDelete.Enabled = (viewUser.GetFocusedDataRow() is DataCentralDataset.UsersRow);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            this.DataHasChanged();
        }
    }
}
